package com.shxc.smarttrade.old.adapter;

import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.RelativeSizeSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.shxc.smarttrade.R;
import com.shxc.smarttrade.old.bean.TransactionDatas;
import com.shxc.smarttrade.old.myinterface.TransactionItemClickListener;
import com.shxc.smarttrade.old.utils.BaseUtils;
import com.zhy.autolayout.utils.AutoUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by jcdev1 on 2017/5/10.
 */

public class TransactionAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    LayoutInflater mInflater;
    Context mContext;
    LinearLayoutManager manager;
    int firstItem = 0;
    int lastItem = 20;
    Map<Integer, Integer> mapBid = new HashMap<>();
    Map<Integer, Integer> mapAsk = new HashMap<>();


    TransactionItemClickListener listener;
    private boolean isShow = false;//控制当前界面是否处于编辑模式
    List<TransactionDatas.DataBean.SymbolsBean> symbolsBeen = new ArrayList<>();
    List<TransactionDatas.DataBean.SymbolsBean> oldSymbolsBeen = new ArrayList<>();
    private int tag;

    public TransactionAdapter(Context mContext, LinearLayoutManager manager) {
        this.mContext = mContext;
        this.manager = manager;
        mInflater = LayoutInflater.from(mContext);
    }

    public void setNewDatas(List<TransactionDatas.DataBean.SymbolsBean> symbolsBeen) {
        this.symbolsBeen = symbolsBeen;
        if (manager != null) {
            firstItem = manager.findFirstVisibleItemPosition();
            lastItem = manager.findLastVisibleItemPosition();
        }
        notifyDataSetChanged();
    }

    public void setOldDatas(List<TransactionDatas.DataBean.SymbolsBean> oldSymbolsBeen) {

        this.oldSymbolsBeen = oldSymbolsBeen;
    }

    //是否编辑数据
    public void isShowDelet(boolean isShow) {
        this.isShow = isShow;
        notifyDataSetChanged();

    }

    //追加数据
    public void addDatas(int position, TransactionDatas.DataBean.SymbolsBean newData) {
        oldSymbolsBeen.add(position, newData);
        notifyItemInserted(position);
    }

    //删除数据
    public void deleteDatas(int position) {
        symbolsBeen.remove(position);
        notifyItemRemoved(position);

    }


    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new TransactionViewholder(mInflater.inflate(R.layout.adapter_traction_product, parent, false));
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
        if (holder instanceof TransactionViewholder) {
            final TransactionDatas.DataBean.SymbolsBean sb = symbolsBeen.get(position);
            int digits = sb.getDigits();
            SpannableString ssLeft = new SpannableString(BaseUtils.getDigitsData(sb.getAsk(), digits));
            RelativeSizeSpan spanLeft = new RelativeSizeSpan((float) 1.5);
            int lengthLeft = ssLeft.length();

            SpannableString ssRight = new SpannableString(BaseUtils.getDigitsData(sb.getBid(), digits) + "");
            int lengthRight = ssRight.length();
            RelativeSizeSpan spanRight = new RelativeSizeSpan((float) 1.5);

            if (sb.getDigits() > 2) {
                ssLeft.setSpan(spanLeft, lengthLeft - 3, lengthLeft - 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
                ssRight.setSpan(spanRight, lengthRight - 3, lengthRight - 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
            } else {
                ssLeft.setSpan(spanLeft, lengthLeft - 4, lengthLeft - 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
                ssRight.setSpan(spanRight, lengthRight - 4, lengthRight - 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
            }

            if (isShow) {
                ((TransactionViewholder) holder).ivDelete.setVisibility(View.VISIBLE);
                ((TransactionViewholder) holder).llRight.setVisibility(View.INVISIBLE);
            } else {
                ((TransactionViewholder) holder).ivDelete.setVisibility(View.GONE);
                ((TransactionViewholder) holder).llRight.setVisibility(View.VISIBLE);
            }
            if (oldSymbolsBeen.size() > 0 && oldSymbolsBeen.size() == symbolsBeen.size()) {
                TransactionDatas.DataBean.SymbolsBean oldsb = oldSymbolsBeen.get(position);
                if (sb.getAsk() > oldsb.getAsk()) {
                    mapAsk.put(position, 1);
                    ((TransactionViewholder) holder).tvLeftBg.setBackgroundResource(R.drawable.red_text_bg);
                    ((TransactionViewholder) holder).tvLeft.setTextColor(mContext.getResources().getColor(R.color.stock_rise_color));
                    if (position > firstItem - 1 && position < lastItem + 1)
                        doAnimation(((TransactionViewholder) holder).tvLeftBg, ((TransactionViewholder) holder).tvLeft);

                } else if (sb.getAsk() < oldsb.getAsk()) {
                    mapAsk.put(position, 0);
                    ((TransactionViewholder) holder).tvLeftBg.setBackgroundResource(R.drawable.green_text_bg);
                    ((TransactionViewholder) holder).tvLeft.setTextColor(mContext.getResources().getColor(R.color.stock_fell_color));
                    if (position > firstItem - 1 && position < lastItem + 1)
                        doAnimation(((TransactionViewholder) holder).tvLeftBg, ((TransactionViewholder) holder).tvLeft);
                } else {

                    if (mapAsk.get(position) != null && mapAsk.get(position) == 0)
                        ((TransactionViewholder) holder).tvLeft.setTextColor(mContext.getResources().getColor(R.color.stock_fell_color));
                    else if (mapAsk.get(position) != null && mapAsk.get(position) == 1)
                        ((TransactionViewholder) holder).tvLeft.setTextColor(mContext.getResources().getColor(R.color.stock_rise_color));
                }

                if (sb.getBid() > oldsb.getBid()) {
                    mapBid.put(position, 1);
                    ((TransactionViewholder) holder).tvRightBg.setBackgroundResource(R.drawable.red_text_bg);
                    ((TransactionViewholder) holder).tvRight.setTextColor(mContext.getResources().getColor(R.color.stock_rise_color));
                    if (position > firstItem - 1 && position < lastItem + 1)
                        doAnimation(((TransactionViewholder) holder).tvRightBg, ((TransactionViewholder) holder).tvRight);

                } else if (sb.getBid() < oldsb.getBid()) {
                    mapBid.put(position, 0);
                    ((TransactionViewholder) holder).tvRightBg.setBackgroundResource(R.drawable.green_text_bg);
                    ((TransactionViewholder) holder).tvRight.setTextColor(mContext.getResources().getColor(R.color.stock_fell_color));
                    if (position > firstItem - 1 && position < lastItem + 1)
                        doAnimation(((TransactionViewholder) holder).tvRightBg, ((TransactionViewholder) holder).tvRight);
                } else {
                    if (mapBid.get(position) != null && mapBid.get(position) == 0)
                        ((TransactionViewholder) holder).tvRight.setTextColor(mContext.getResources().getColor(R.color.stock_fell_color));
                    else if (mapBid.get(position) != null && mapBid.get(position) == 1)
                        ((TransactionViewholder) holder).tvRight.setTextColor(mContext.getResources().getColor(R.color.stock_rise_color));
                }
            }

            ((TransactionViewholder) holder).tvName.setText(sb.getSymbolCn());
            ((TransactionViewholder) holder).tvNameEn.setText(sb.getSymbolEn());
            ((TransactionViewholder) holder).tvLeft.setText(ssLeft);
            ((TransactionViewholder) holder).tvRight.setText(ssRight);
            ((TransactionViewholder) holder).tvLeftBg.setText(ssLeft);
            ((TransactionViewholder) holder).tvRightBg.setText(ssRight);
            ((TransactionViewholder) holder).tvCenter.setText(format1(sb.getAsk(), sb.getBid(), digits) + "");
//            ((TransactionViewholder) holder).tvCenter.setText(getAskAndBidSub(sb.getAsk(), sb.getBid()) + "");

            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    listener.itemClick(sb, position);
                }
            });
            ((TransactionViewholder) holder).ivDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    listener.clickToDelete(sb, position);
                }
            });
        }

    }

    @Override
    public int getItemCount() {
        return symbolsBeen == null ? 0 : symbolsBeen.size();
    }

    public class TransactionViewholder extends RecyclerView.ViewHolder {
        @BindView(R.id.tv_left)
        TextView tvLeft;
        @BindView(R.id.tv_center)
        TextView tvCenter;
        @BindView(R.id.tv_right)
        TextView tvRight;
        @BindView(R.id.tv_left_bg)
        TextView tvLeftBg;
        @BindView(R.id.tv_right_bg)
        TextView tvRightBg;
        @BindView(R.id.iv_delete)
        ImageView ivDelete;
        @BindView(R.id.ll_right)
        LinearLayout llRight;
        @BindView(R.id.tv_name)
        TextView tvName;
        @BindView(R.id.tv_name_en)
        TextView tvNameEn;

        TransactionViewholder(View view) {
            super(view);
            ButterKnife.bind(this, view);
            AutoUtils.autoSize(view);

        }
    }

    public void setOnItemClickListener(TransactionItemClickListener listener) {
        this.listener = listener;
    }

    /**
     * 渐变动画
     */
    private void doAnimation(final View view, final View view2) {
        final AlphaAnimation alpha = new AlphaAnimation(1, 0);
        alpha.setDuration(500);
        alpha.setFillAfter(true);
//        alpha.setRepeatMode(Animation.REVERSE);  //设置重复模式
//        alpha.setRepeatCount(5);  //设置重复次数
        view.startAnimation(alpha);
        alpha.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                view.setVisibility(View.VISIBLE);
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                view.setVisibility(View.INVISIBLE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

    }

    /**
     * 处理ask和bid的差值
     *
     * @param ask
     * @param bid
     * @return
     */
    public static String format1(double ask, double bid, int digits) {

//        String buff = (ask.floatValue() + "");
//        int len1 = buff.length();
//        int len2 = buff.indexOf(".");
//        return ask.subtract(bid).abs().multiply(BigDecimal.TEN.pow(len1 - len2 - 1)).intValue();

        double a = Math.pow(10, digits) * ask;
        double b = Math.pow(10, digits) * bid;
        double result = Math.abs(a - b);
        String str = BaseUtils.getDigitsData(result / 10, 1);
        if (str.lastIndexOf("0") == str.length() - 1)
            return str.substring(0, str.length() - 2);
        else
            return str;
    }

    /**
     * 用于精确计算Double类型的数据
     *
     * @param ask
     * @param bid
     * @return
     */
//    public static int getAskAndBidSub(Double ask, Double bid) {
//        int len1 = ask.toString().length();
//        int len2 = bid.toString().length();
//        int index1 = ask.toString().indexOf(".");
//        int index2 = bid.toString().indexOf(".");
//        int result1 = len1 - index1 - 1;
//        int result2 = len2 - index2 - 1;
//
//        Double db = Arith.sub(ask, bid);
//        Double dou = Arith.round(db, result1 > result2 ? result1 : result2);
//        BigDecimal bd = new BigDecimal(dou);
//        double last = bd.abs().multiply(BigDecimal.TEN.pow(result1 > result2 ? result1 : result2)).doubleValue();
//        return (int) Arith.round(last, result1 > result2 ? result1 : result2);
//    }
}
